import Vue from 'vue';
import qs from 'qs';

class httpClient {

    //封装http GET
    get(uri, params, config) {
        config = config ? config : {};
        config.method = "get";
        return this.ajax(uri, { params: params }, config)
    }

    //封装http POST
    post(uri, params, config) {
        config = config ? config : {};
        config.method = "post";
        return this.ajax(uri, params, config);
    }

    //封装http PUT
    put(uri, params, config) {
        config = config ? config : {};
        config.method = "put";
        return this.ajax(uri, params, config);
    }

    //封装http DELETE
    delete(uri, params, config) {
        config = config ? config : {};
        config.method = "delete";
        return this.ajax(uri, params, config);
    }

    ajax(uri, params, config) {
        config = config ? config : {};
        var settings = { check: true, method: "get" };
        for (var key in config) {
            settings[key] = config[key];
        }

        //FormData上传图片时不序列化params，post和put时序列化params
        if ((settings.method == "post" && !(params instanceof FormData)) || settings.method == "put" || settings.method == "delete") {
            //params = qs.stringify(params);
        }

        console.log(params)

        if (settings.method == "post"){
            params = qs.stringify(params);
            //uri += '?' + params
        }

        console.log(params)

        //delete的传参
        if (settings.method == 'delete') {
            uri += '?' + params
        }

        return Vue.http[settings.method](uri, params);
    }

}

export default new httpClient();